import { getArtistPage } from '@/services/global/base';
import { Select, Avatar, Tag } from 'antd';
import { debounce } from 'lodash';
import { useState } from 'react';
import { IsOfficial } from '@/constants';

import styles from './style.less';

const { Option } = Select;

type Props = {
  value?: string;
  onChange?: (value: any) => void;
  [key: string]: any;
};

const SelectArtist: React.FC<Props> = ({ value, onChange, ...rest }) => {
  const [data, setData] = useState<any[]>([]);
  const { mode } = rest;

  const getArtistList = async (searchValue: string) => {
    const res = await getArtistPage(searchValue);
    setData(res.data.list);
  };

  const debounceSearch = debounce(getArtistList, 500);

  const handleSearch = (searchValue: string) => {
    if (searchValue === '') {
      setData([]);
      return;
    }

    debounceSearch(searchValue);
  };

  const handleChange = (ret: any) => {
    if (onChange) {
      if (mode === 'multiple') {
        const record = ret.map((singer: any) => {
          if (typeof singer === 'number') {
            return data.find((item: any) => item.singerId === singer);
          }
          return singer;
        });
        onChange(record);
      } else {
        onChange(ret);
      }
    }
  };

  const options = data.map((d) => (
    <Option key={d.singerId} value={d.singerId}>
      <span>
        <Avatar
          src={d.singerPhotos && d.singerPhotos[0]?.photoUrl}
          style={{ marginRight: 10 }}
          className={styles.avatar}
        />
        {`${d.singerId} -@- ${d.singerName}`}
      </span>
    </Option>
  ));

  const tagRender = (props: any) => {
    const { label, closable, onClose } = props;

    return (
      <Tag
        closable={closable}
        onClose={onClose}
        style={{ marginRight: 3 }}
        className={`${styles.tag} ant-select-selection-item`}
      >
        <span
          className="ant-select-selection-item-content"
          title={`${label.singerName}(${label.singerId})`}
        >{`${label.isOfficial === IsOfficial.NOT_OFFICIAL ? '未匹配' : label.singerId} -@- ${
          label.singerName
        }`}</span>
      </Tag>
    );
  };

  return (
    <Select
      showSearch
      value={value}
      placeholder="输入艺人ID或名字搜索"
      filterOption={false}
      onSearch={handleSearch}
      onChange={handleChange}
      notFoundContent={null}
      tagRender={mode === 'multiple' ? tagRender : undefined}
      {...rest}
    >
      {options}
    </Select>
  );
};

export default SelectArtist;
